package com.googlecode.connectlet.tsa;

import java.io.IOException;

import sun.security.util.DerInputStream;
import sun.security.util.DerOutputStream;
import sun.security.util.DerValue;
import sun.security.util.ObjectIdentifier;
import sun.security.x509.AlgorithmId;

public class MessageImprint {
	public static ObjectIdentifier MD2 = AlgorithmId.MD2_oid;
	public static ObjectIdentifier MD5 = AlgorithmId.MD5_oid;
	public static ObjectIdentifier SHA1 = AlgorithmId.SHA_oid;
	public static ObjectIdentifier SHA256 = AlgorithmId.SHA256_oid;
	public static ObjectIdentifier SHA384 = AlgorithmId.SHA384_oid;
	public static ObjectIdentifier SHA512 = AlgorithmId.SHA512_oid;

	private ObjectIdentifier algorithm;
	private byte[] digest;

	private MessageImprint(MessageImprint messageImprint) {
		this.algorithm = messageImprint.algorithm;
		this.digest = messageImprint.digest;
	}

	public MessageImprint(ObjectIdentifier algorithm, byte[] digest) {
		this.algorithm = algorithm;
		this.digest = digest;
	}

	public MessageImprint(byte[] encoded) throws IOException {
		DerValue[] ders = new DerInputStream(encoded).getSequence(0);
		if (ders.length < 2) {
			throw new IOException("Invalid DER Format");
		}
		algorithm = ders[0].toDerInputStream().getOID();
		digest = ders[1].getOctetString();
	}

	public MessageImprint(TstInfo tstInfo) {
		this(tstInfo.getMessageImprint());
	}

	public MessageImprint(TimeStampReq tsReq) {
		this(tsReq.getMessageImprint());
	}

	public ObjectIdentifier getAlgorithm() {
		return algorithm;
	}

	public byte[] getDigest() {
		return digest;
	}

	public byte[] getEncoded() throws IOException {
		DerOutputStream alg = new DerOutputStream();
		alg.putOID(algorithm);
		alg.putNull();
		DerOutputStream mi = new DerOutputStream();
		mi.write(DerValue.tag_Sequence, alg);
		mi.putOctetString(digest);
		DerOutputStream dos = new DerOutputStream();
		dos.write(DerValue.tag_Sequence, mi);
		return dos.toByteArray();
	}
}